package com.kaibes.orm.curd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateBuilder {

    private String tableName;
    protected Map<String, Object> data;
    protected List<Query> queries;
    
    public UpdateBuilder() {
        data = new HashMap<>();
        queries = new ArrayList<Query>();
    }
    
    public UpdateBuilder setData(Map<String, Object> data) {
        this.data = data;
        return this;
    }
    
    public UpdateBuilder setValue(String key, Object value) {
        data.put(key, value);
        return this;
    }
    
    public UpdateBuilder setValue(String key, Object value, boolean flag) {
        if (flag) {
            data.put(key, value);
        }
        return this;
    }
    
    public UpdateBuilder setNull(String key) {
        data.put(key, null);
        return this;
    }
    
    public UpdateBuilder setNull(String key, boolean flag) {
        if (flag) {
            data.put(key, null);
        }
        return this;
    }
    
    public UpdateBuilder delValue(String... keys) {
        for (String key : keys) {
            data.remove(key);
        }
        return this;
    }
    
    public Object getValue(String key) {
        return data.get(key);
    }
    
    public UpdateBuilder createQueryById(String name) {
        Object id = data.get(name);
        if (id != null) {
            addQuery(QueryBuilder.newBuilder().eq(name, id).build());
            data.remove(name);
        }
        return this;
    }
    
    public UpdateBuilder setQueries(List<Query> queries) {
        this.queries = queries;
        return this;
    }
    
    public UpdateBuilder addQuery(Query query) {
        queries.add(query);
        return this;
    }
    
    public void setTableName(String tableName) {
        this.tableName = tableName;
    }
    
    public Update build() {
        Update update = new Update();
        update.setData(data);
        update.setQueries(queries);
        update.setTableName(tableName);
        return update;
    }
    
    public static UpdateBuilder newBuilder() {
        return new UpdateBuilder();
    }
}
